package cn.lkp.mall.cart.interceptor;

import cn.lkp.common.constant.AuthServerConstant;
import cn.lkp.common.constant.CartConstant;
import cn.lkp.common.vo.MemberVo;
import cn.lkp.mall.cart.vo.UserInfoTo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 购物车拦截器
 * 在执行目标方法cartListPage()之前，检查用户的登录状态，并封装传递给Controller目标请求
 */
//将拦截器加入web配置后，就不用再加入容器了
//@Component
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        HttpSession session = request.getSession();
        MemberVo vo = (MemberVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        UserInfoTo userInfoTo = new UserInfoTo();
        if(vo != null){
            //用户登录了
            userInfoTo.setUserId(vo.getId());
        }
        //用户没登录，取出request里面带来的cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0){
            for (Cookie cookie : cookies) {
                //将名字为user-key的cookie抽取为常量
                //String name = cookie.getName();
                if(cookie.getName().equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                    userInfoTo.setUserKey(cookie.getValue());
                    //标记为已是临时用户
                    userInfoTo.setTempUser(true);
                }
            }
        }
        //第一次使用购物车功能，如果没有临时用户身份，系统自动创建一个
        if(StringUtils.isEmpty(userInfoTo.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }
        //放行前将数据放入threadLocal
        threadLocal.set(userInfoTo);
        //放行以便执行目标方法
        return true;
    }

    /**
     * 目标方法执行完毕后，让浏览器保存名称为user-key的cookie
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //让浏览器保存名称为user-key的cookie
        UserInfoTo userInfoTo = threadLocal.get();
        if(!userInfoTo.getTempUser()){
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME,
                    threadLocal.get().getUserKey());
            cookie.setDomain("mall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
